from django.http import HttpResponse
from django.shortcuts import redirect,render
from web import models
from web.forms.level_form import *

def level_list(request):
    queryset = models.Level.objects.filter(active=1)
    return render(request, 'level_list.html', {'queryset': queryset})

def level_add(request):
    if request.method == "GET":
        form = LevelAddForm()
        return render(request, 'form.html', {'form': form})

    form = LevelAddForm(request.POST)
    if not form.is_valid():
        return render(request, 'form.html', {'form': form})


    form.save()
    return redirect('level_list')

def level_edit(request, pk):
    level_obj = models.Level.objects.filter(active=1, pk=pk).first()
    if request.method == "GET":
        form = LevelAddForm(instance=level_obj)
        return render(request, 'form.html', {'form': form})

    form = LevelAddForm(instance=level_obj, data=request.POST)
    if not form.is_valid():
        return render(request, 'form.html', {'form': form})

    form.save()
    return redirect('level_list')
def level_delete(request, pk):
    exists = models.Customer.objects.filter(level=pk).exists()
    if not exists:
        models.Level.objects.filter(id=pk).update(active=0)
    return redirect('level_list')